package com.yj.springbootmybatis.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yj.springbootmybatis.enums.RedisConstant;
import com.yj.springbootmybatis.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * token 拦截器
 */
@Slf4j
public class UserTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 在访问controller 之前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("拦截器被拦截了。。。。");

        //false:请求被拦截器拦截，驳回，身份验证出现问题
        //true:验证成功，放行

        // 1.先从请求头中获取 userId 和 token,如果获取不到则从 请求路径中获取
        String userId = request.getHeader("userId");
        String token = request.getHeader("token");

        log.info("userId:{}", userId);
        log.info("token:{}", token);

        if (StringUtils.isBlank(userId)) {
            userId = request.getParameter("userId");
        }
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
        }

        if (StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(token)){
            String redisToken = redisTemplate.opsForValue().get(RedisConstant.REDIS_USER_TOKEN.key + ":" + userId);
            log.info("redisToken:{}", redisToken);

            if (StringUtils.isNotBlank(redisToken) && StringUtils.equalsIgnoreCase(token, redisToken)) {
                return true;
            }else {
                errorMsgResp(response,ResponseUtil.error().message("身份信息有误！"));
                return false;
            }
        }else {
            errorMsgResp(response,ResponseUtil.error().message("请登录！"));
            return false;
        }

    }

    //返回错误的json 信息
   public void errorMsgResp(HttpServletResponse response,ResponseUtil responseUtil){

        response.setContentType("text/json");
        response.setCharacterEncoding("utf-8");

       try(ServletOutputStream out = response.getOutputStream();) {

           out.write(objectMapper.writeValueAsString(responseUtil).getBytes("utf-8"));
           out.flush();
       } catch (Exception e){
           throw new RuntimeException();
       }
   }

    /**
     * 在访问controller 之后，渲染之前
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 在访问controller 之后，渲染之后
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
